<template>
    <userDialog
        v-model="visible"
        :dialogTitle="`${userDialogType}用户`"
        width="880px"
        @open="init"
        @handleCloseDialog="handleCloseDialog(false)"
    >
        <template v-slot:userDiagContent>
            <dialogFormContent title="基本信息">
                <template v-slot:form_info="{ isShowInfoFold }">
                    <div v-show="isShowInfoFold">
                        <el-form
                            :rules="addUserFromRules"
                            :model="form"
                            class="user_form_content"
                            ref="queryFormRef"
                        >
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item
                                        label="真实姓名："
                                        prop="realname"
                                    >
                                        <el-input
                                            v-model="form.realname"
                                            placeholder="请输入真实姓名"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="手机号：" prop="phone">
                                        <el-input
                                            v-model="form.phone"
                                            placeholder="请输入手机号码"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item
                                        label="所属单位："
                                        prop="compony_id"
                                    >
                                        <el-select
                                            v-model="form.compony_id"
                                            placeholder="请选择"
                                        >
                                            <el-option
                                                v-for="item in companyList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item
                                        label="所属地域："
                                        prop="part"
                                    >
                                        <el-cascader
                                            v-model="form.part"
                                            :props="countryProp"
                                            clearable
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item
                                        label="详细地址："
                                        prop="address"
                                    >
                                        <el-input
                                            type="textarea"
                                            autosize
                                            v-model="form.address"
                                            placeholder="请输入详细地址"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </template>
            </dialogFormContent>
            <dialogFormContent title="权限信息">
                <template v-slot:form_info="{ isShowInfoFold }">
                    <div v-show="isShowInfoFold">
                        <rolePerssion
                            ref="rolePerssionRef"
                            :checkList="roleList"
                        ></rolePerssion>
                    </div>

                    <ShowMore
                        show-text-tips="添加其他权限(自定义)"
                        close-text-tips="隐藏其他权限(自定义)"
                        background="#f6f9ff"
                        class="mt-20px"
                    >
                        <template v-slot:form_info="{ visible }">
                            <div v-show="visible">
                                <appRolePerssion
                                    ref="appRolePerssionRef"
                                    class="mt-20px"
                                    :checkList="appList"
                                ></appRolePerssion>
                                <menusManagerSlelet
                                    ref="menusManagerSleletRef"
                                    v-model:menuList="menuList"
                                ></menusManagerSlelet>
                            </div>
                        </template>
                    </ShowMore>
                </template>
            </dialogFormContent>
            <div class="btnStyle mt-20px">
                <el-button type="primary" @click="upData()"> 提交 </el-button>
                <el-button type="info" @click="handleCloseDialog()">
                    重置
                </el-button>
            </div>
        </template>
    </userDialog>
</template>

<script setup lang="ts">
import UserAPI from "@/api/system/user";
import MenuAPI from "@/api/system/menu";
import { getLeaveOneToThreeOption } from "@/views/system/userManager/index";
import { addUserFromRules } from "@/views/system/userManager/index";
const emit = defineEmits(["reFresh"]);
const visible = defineModel("modelValue", {
    type: Boolean,
    required: true,
    default: false,
});

const props = defineProps({
    userDialogType: {
        required: true,
        default: () => "添加" as any,
    },
    userId: {
        required: true,
        default: () => "",
    },
});
const queryFormRef = ref();
const rolePerssionRef = ref();
const appRolePerssionRef = ref();
const menusManagerSleletRef = ref();
const form = ref({
    realname: "",
    phone: "",
    compony_id: "",
    part: [],
    address: "",
});

const checkBoxName = ref("角色(多选)：");

// 下拉列表类型
interface elselect {
    label: string;
    value: string;
}
const roleList = ref([] as elselect[]);
const appList = ref([] as elselect[]);
const companyList = ref([] as elselect[]);
const menuList = ref([] as any[]);

async function getAllCommonUserInfo() {
    return Promise.all([
        // 获取单位列表
        UserAPI.getCompany().then((data) => {
            companyList.value = data.map((item: any) => {
                return {
                    label: item.name,
                    value: item.id,
                };
            });
        }),
        // 获取角色列表
        UserAPI.getRoleList().then((data) => {
            roleList.value = data.map((item: any) => {
                return {
                    label: item.type_name,
                    value: item.id,
                };
            });
        }),
        // 获取app列表
        UserAPI.getAppList().then((data) => {
            appList.value = data.map((item: any) => {
                return {
                    label: item.name,
                    value: item.id,
                };
            });
        }),
        // 获取菜单列表
        MenuAPI.getOptions().then((data) => {
            deepEdit(data);
            menuList.value = data;
        }),
    ]).catch((error) => {
        throw error;
    });
}

//
function deepEdit(data: any, parent = null) {
    data.forEach((item: any) => {
        item.chooseStatus = "noneSelect";
        item.choosed = false;
        item.actived = false;
        item.parent = parent;
        if (item.children) {
            deepEdit(item.children, item);
        }
    });
}

// 选择村镇
const countryProp = {
    lazy: true,
    checkStrictly: true,
    lazyLoad(node: any, resolve: any) {
        getLeaveOneToThreeOption(node).then((res) => {
            resolve(res);
        });
    },
};

// 初始化表单
async function init() {
    await getAllCommonUserInfo();

    if (props.userDialogType === "编辑" && props.userId) {
        await getUserDetail();
    }
}

// 获取编辑人员信息
async function getUserDetail() {
    let id = props.userId;
    await UserAPI.getUserInfo(id)
        .then((data: any) => {
            putUserDetail(data);
        })
        .catch((err: any) => {
            console.log(err);
        });
}

// 回写详情信息
async function putUserDetail(data: any) {
    //基本信息
    form.value.address = data.detail.address;
    form.value.compony_id = data.detail.compony_id;
    form.value.part = [
        data.detail.province,
        data.detail.city,
        data.detail.district,
        data.detail.town,
        data.detail.village,
    ] as any;
    form.value.phone = data.detail.phone;
    form.value.realname = data.detail.realname;

    //角色权限
    let arr: any = [];
    roleList.value.forEach((item: any) => {
        if (data.detail.alltype.includes(String(item.value))) {
            arr.push(String(item.value));
        }
    });
    rolePerssionRef.value.formObj.roleCheckoutList = arr;
    rolePerssionRef.value.formObj.defaultUser = data.detail.user_type_id;

    //小程序权限
    appRolePerssionRef.value.appCheckoutList =
        data.menus.front_operation_ids.map((item: any) => {
            return (item = Number(item));
        });
    setChooseData(menuList.value, data.menus.menu_ids);
}

// 选取
const setChooseData = (data: any, resData: any) => {
    data.forEach((ele: any) => {
        if (resData.includes(String(ele.value))) {
            menusManagerSleletRef.value.menusSelect.menuItemChoose(ele, true);
        }

        if (ele.children) {
            setChooseData(ele.children, resData);
        }
    });
};

// 提交
async function upData() {
    //表单校验
    const queryFormIsValid = await queryFormRef.value.validate(
        (isValid: boolean) => {
            return isValid;
        }
    );
    //角色校验
    const rolePerssionValid = await rolePerssionRef.value.roleValidation();
    if (!queryFormIsValid || !rolePerssionValid) {
        return;
    }

    // 表单参数
    let [province, city, district, town, village] = form.value.part;
    // 表单参数
    let formParams = {
        realname: form.value.realname,
        phone: form.value.phone,
        compony_id: form.value.compony_id,
        address: form.value.address,
        province: province || "",
        city: city || "",
        district: district || "",
        town: town || "",
        village: village || "",
    };
    // 角色参数
    let roleParams = {
        user_type_id: rolePerssionRef.value.formObj.defaultUser,
        alltype: rolePerssionRef.value.formObj.roleCheckoutList,
    };
    let appParams = {
        front_operation_ids: appRolePerssionRef?.value?.appCheckoutList || [],
    };
    let menusManagerParams = {
        menu_ids:
            menusManagerSleletRef.value.choosedList?.map((item: any) => {
                return item.value;
            }) || [],
    };

    let api = UserAPI.addUser;
    let params: any = {
        ...formParams,
        ...roleParams,
        ...appParams,
        ...menusManagerParams,
    };
    if (props.userDialogType === "编辑" && props.userId) {
        api = UserAPI.editUserInfo;
        params.id = props.userId;
    }
    await api(params)
        .then((data: any) => {
            console.log(data);
            visible.value = false;
            emit("reFresh");
            ElMessage.success(`${props.userDialogType}成功`);
        })
        .catch((err: any) => {
            console.log(err);
        });
}

function handleCloseDialog(visibleValue = true) {
    if (!visibleValue) {
        visible.value = visibleValue;
    }

    queryFormRef.value.resetFields();
    queryFormRef.value.clearValidate();

    rolePerssionRef.value.roleCheckRef.resetFields();
    rolePerssionRef.value.roleCheckRef.clearValidate();

    appRolePerssionRef.value.appCheckoutList = [];

    menusManagerSleletRef.value.allReset();
}
</script>

<style lang="scss" scoped>
.btnStyle {
    padding: 0 255px;
    @include flexLayout;
    justify-content: space-between;
    .el-button {
        font-size: 16px;
        padding: 20px 40px;
    }
}
.user_form_content {
    :deep(.el-form-item) {
        display: flex;

        label {
            width: 94px;
        }
        .el-input,
        .el-cascader,
        .el-select {
            height: 32px;
            width: 100%;
            .el-select__wrapper {
                height: 32px;
                line-height: 32px;
            }
        }
    }
}
</style>
